from jose import jwt
from datetime import datetime, timedelta


SECRET_KEY = "your-access-token-secret"
REFRESH_SECRET = "your-refresh-token-secret"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 15    # 15 分钟
REFRESH_TOKEN_EXPIRE_DAYS = 7       # 7 天


def create_access_token(data: dict, expires_delta: timedelta = None):   # （短期有效） → 用于访问接口
    to_encode = data.copy()
    expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)


def create_refresh_token(data: dict):   # (长期有效） → 用于刷新 access_token
    expire = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
    to_encode = data.copy()
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, REFRESH_SECRET, algorithm=ALGORITHM)


def  verify_refresh_token(token: str):
    try:
        payload = jwt.encode(token, REFRESH_SECRET, algorithm=[ALGORITHM])
        return payload
    except Exception:
        return None